package com.hmjk.health.health;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.util.GlycoseReferenceSet;
import com.hmjk.health.views.SwitchButton;
import com.hmjk.health.views.SwitchButton.OnChangeListener;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

public class HealthDeviceParam extends Activity implements OnClickListener{
	private final String TAG = HealthDeviceParam.class.getSimpleName();
	private HealthApp mApp = null;
	
	private String tid = "", subcode = "" ;
	private boolean isAdmin = false;
	
	private SwitchButton mVoiceSwitch = null;
	private Spinner mUnitSpinner = null;
	private TextView mVoiceText = null, mUnitText = null;
	
	private GlycoseReferenceSet setData;
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		logd("onCreate");
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mApp = (HealthApp)getApplication();
		
		setContentView(R.layout.health_device_param);
		ImageButton butBack = (ImageButton)findViewById(R.id.back);
		butBack.setOnClickListener(this);
		Button butCommit = (Button)findViewById(R.id.commit);
		butCommit.setOnClickListener(this);
		
		Intent i = getIntent();
        tid = i.getStringExtra("tid");
        subcode = i.getStringExtra("subcode");
        logd("tid=" + tid + ", subcode=" + subcode);
        if(i.getIntExtra("admin", 0) == 1){
        	isAdmin = true;
        }
        
        mVoiceSwitch = (SwitchButton)findViewById(R.id.switchVoice);
        mUnitSpinner = (Spinner)findViewById(R.id.spinnerunit);
        mVoiceText = (TextView)findViewById(R.id.textVoice);
        mUnitText = (TextView)findViewById(R.id.textunit);
        
        if(isAdmin == false){
        	mVoiceSwitch.setVisibility(View.GONE);
        	mUnitSpinner.setVisibility(View.GONE);
        	mVoiceText.setVisibility(View.VISIBLE);
        	mUnitText.setVisibility(View.VISIBLE);
        	
        	butCommit.setVisibility(View.INVISIBLE);
        }else {
        	mVoiceSwitch.setVisibility(View.VISIBLE);
        	mUnitSpinner.setVisibility(View.VISIBLE);
        	mVoiceText.setVisibility(View.GONE);
        	mUnitText.setVisibility(View.GONE);
        	
        	String unitArray[] = getResources().getStringArray(R.array.unitarray);
            ArrayAdapter<String> adapterUnit = new ArrayAdapter<String>(this, R.layout.spinner_item, unitArray);
            adapterUnit.setDropDownViewResource(R.layout.spinner_item);
            mUnitSpinner.setAdapter(adapterUnit);
            mUnitSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> adapter, View v,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					setData.unit = mUnitSpinner.getSelectedItemPosition();
				}

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub
					
				}
			});
            
            mVoiceSwitch.setOnChangeListener(new OnChangeListener() {
				
				@Override
				public void onChange(SwitchButton sb, boolean state) {
					// TODO Auto-generated method stub
					if(state){
						setData.voice = 1;
					}else {
						setData.voice = 0;
					}
				}
			});
		}
        
        
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		IntentFilter filter = new IntentFilter();
		filter.addAction(DataManager.DATA_COMMIT_RESULT);
		registerReceiver(mReceiver, filter);
		
		queryGlucoseDetail();
		updateViews();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unregisterReceiver(mReceiver);
	}
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if(action.equals(DataManager.DATA_COMMIT_RESULT)){
				mApp.dismissWaiting();
				String type = intent.getStringExtra("type");
				if(type.equals(DataManager.F_GLYCOSE_SET)){
					String state = intent.getStringExtra("state");
					int code = intent.getIntExtra("code", 500);
					if(state.equals("00") && (code == 200)){
						mApp.showAlertDialog(HealthDeviceParam.this, getResources().getString(R.string.health_param_set_ok),
								R.string.ok, new OnClickListener() {
									
									@Override
									public void onClick(View arg0) {
										// TODO Auto-generated method stub
										HealthDeviceParam.this.setResult(RESULT_OK);
										finish();
									}
								});
						return;
					}
					mApp.showAlertDialog(HealthDeviceParam.this, getResources().getString(R.string.health_param_set_error), null);
				}
			}
		}
		
	};
	
	private void queryGlucoseDetail(){
		String[] args = {tid};
		setData = (GlycoseReferenceSet) mApp.getDataManager().checkData(DataManager.F_GLYCOSE_SET, args);
		
	}
	
	private void updateViews(){
		if (setData == null) {
			return;
		}
		
		if(isAdmin){
			boolean flage = true;
			if(setData.voice == 0){
				flage = false;
			}
			mVoiceSwitch.setFlage(flage);
			
			mUnitSpinner.setSelection(setData.unit);
		}else {
			if(setData.voice == 0){
				mVoiceText.setText(R.string.fence_closed);
			}else {
				mVoiceText.setText(R.string.fence_open);
			}
			
			String unitArray[] = getResources().getStringArray(R.array.unitarray);
			mUnitText.setText(unitArray[setData.unit]);
		}
	}
	
	private void commitDeviceParam(){
		mApp.showWaitting(this, null);
		mApp.getDataManager().commitData(DataManager.F_GLYCOSE_SET, setData);
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.back:{
			finish();
		}break;
		
		case R.id.commit:{
			mApp.showConfirmDialog(this, getResources().getString(R.string.health_param_set_confirm), new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(v.getId() == R.id.alert_but1){
						commitDeviceParam();
					}
				}
			});
		}
		}
		
	}

}
